/*
 * DA3.c
 *
 * Created: 3/5/2014 9:46:58 PM
 *  Author: Vincent
 */ 


#include "avr/io.h"
#include "avr/interrupt.h"

volatile int ctrInt = 0;

int main ()
{
	//this will setup counter 1 as waveform generator
	DDRD |= 1<<PD0|1<<PD1;			//make DDRD.0 and DDRD.1 as output
	DDRB = 0xFF;					//make PORTB output
	OCR1A = 0x3D0;					//X defined with 250ms => 976 cycles
	TCCR1A = 1<<WGM12;				//CTC mode will set the interrupt, 
	TCCR1B = 1<<CS12;				//internal clk, 256 prescaler
	TIMSK1 = (1<<OCIE1A);			//enable Timer1A compare match interrupt

	//this will setup timer0 as counter
	TCCR0A = 0x00;						//Timer 0 in normal (counter)mode
	TCCR0B = 1<<CS02|1<<CS01|1<<CS00;	//set ext clk source at T0 pin, no prescaler,
	//clk on rising edge at PORTD.4

	//this will enable interrupt on INT0 for PD1(9th bit of the LED)
	EICRA = (1<<ISC01);    //enable external interrupt ISC01 on falling edge of INT0
	EIMSK = (1<<INT0);     //enable external Mask INT0(PD2)
	sei ();					//enable interrupts
	while (1)
	{
		PORTB = TCNT0;		//output timer0 counter to portb
	}
}



ISR (TIMER1_COMPA_vect)	//ISR for Timer1 compare match
{
	PORTD ^= 1<<PD0;		//toggle PORTD.0
	TCNT1 = 0;
}

ISR (INT0_vect) //ISR for external interrupt 0
{
	++ctrInt;
	if (ctrInt == 16)
	{
		PORTD ^= (1<<PD1); //toggle PORTD.1
		ctrInt = 0;
	}
}

//PD0 will be the waveform
//PORTB will be the counter
//PD1 will be the 9th bit of the led bar
//PD0(timer 1 waveform) is connected to PD4(timer0 input clk)
//PD2/INT0 is connected to pd0(timer 1 waveform)
//must choose appropriate period and pulse width